<template>
  <div id="contain">
    <div class="box">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="广告名称" style="width: 500px" :rules="rules">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="上传广告图片" :rules="rules">
          <el-upload
            action=""
            list-type="picture-card"
            :file-list="fileList"
            :http-request="upload"
            :before-upload="beforeUpload"
            ref="uploadGgao"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告内容" :rules="rules">
          <el-input type="textarea" :rows="8" v-model="form.content"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :disabled='!this.fileUrl'>立即创建</el-button>
          <el-button @click="back">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import utils from '@/assets/utils'

export default {
  data() {
    return {
      token: window.localStorage.getItem("token"),
      form: {},
      rules: { required: true },
      fileList: [],
      imgForm: new FormData(),
      imgUrl: "",
      fileName: "",
      fileUrl: "",
    };
  },
  methods: {
    onSubmit() {
      // console.log(this.form);
      this.$axios({
        method: "post",
        url: "/ad/add",
        headers: { token: this.token },
        data: this.form,
      }).then((res) => {
        // console.log(res);
        if (res.data.code !== 0) {
          this.$message.error(res.data.msg);
          return false;
        }
        this.$message.success("创建成功");
        this.back()
        utils.$emit('getMyGgaoList')
        return true
        // this.$router.go(0)
      });
    },
    back() {
      this.form = {};
      this.fileUrl = ''
      this.$refs['uploadGgao'].clearFiles()
    },
    upload() {
      this.$axios({
        method: "post",
        url: "/oss/upload/advertise",
        headers: { token: this.token },
        data: this.imgForm,
      }).then((res) => {
        // console.log(res);
        let data = res.data;
        if (data.code !== 0) {
          this.$message.error(res.data.msg);
          return false;
        }
        this.fileName = data.name;
        this.fileUrl = data.url;
        this.form.pic = this.fileUrl;
        // console.log(2222222);
        // console.log(this.form);
        // this.$message.success("上传成功");
      });
    },
    beforeUpload(file) {
      if (file) {
        this.imgForm.append("file", file);
      } else {
        return false;
      }
    },
  },
};
</script>
<style  scoped>
.box {
  width: 900px;
  margin: 30px;
}
</style>>
